﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using MediaInfoLib;

namespace MovieRenamer
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
			
			splitContainer.Panel2Collapsed = true;
			bindingSource.DataSource = new BindingList<MovieFile>();
			statusProgressBar.Visible = false;
		}
		
		void AddFolderToolButtonClick(object sender, EventArgs e)
		{
			if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)
			{
				DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog.SelectedPath);
				foreach (FileInfo fileInfo in dir.GetFiles())
				{
					bindingSource.Add(new MovieFile(fileInfo.FullName));
				}
			}
		}
		
		void AddFileToolButtonClick(object sender, EventArgs e)
		{
			if (openFileDialog.ShowDialog(this) == DialogResult.OK)
			{
				foreach (string fileName in openFileDialog.FileNames)
				{
					bindingSource.Add(new MovieFile(fileName));
				}
			}
		}
		
		void FilesDataGridViewSelectionChanged(object sender, EventArgs e)
		{
			ShowMediaInfo();
		}
		
		void MediaInfoToolButtonCheckedChanged(object sender, EventArgs e)
		{
			splitContainer.Panel2Collapsed = !mediaInfoToolButton.Checked;
			ShowMediaInfo();
		}
		
		private void ShowMediaInfo()
		{
			if (!splitContainer.Panel2Collapsed && bindingSource.Current != null)
			{
				MovieFile movieFile = bindingSource.Current as MovieFile;
				
				MediaInfo mediaInfo = new MediaInfo();
				mediaInfo.Open(movieFile.FullFileName);
				
				mediaInfoRichTextBox.Text = mediaInfo.Inform();
				mediaInfoRichTextBox.Text += "\n";
				mediaInfoRichTextBox.Text += mediaInfo.Option("Info_Codecs");
				
				mediaInfo.Close();
			}
		}
		
		void FindMatchedMoviesToolButtonClick(object sender, EventArgs e)
		{
			Cursor = Cursors.WaitCursor;
			
			statusLabel.Text = string.Empty;
			statusProgressBar.Value = 0;
			statusProgressBar.Minimum = 0;
			statusProgressBar.Step = 1;
			statusProgressBar.Visible = true;
			
			ArrayList moviesToSearch =  new ArrayList();
			foreach (MovieFile movieFile in bindingSource)
			{
				if (movieFile.Rename)
				{
					moviesToSearch.Add(movieFile);
				}
			}
			statusProgressBar.Maximum = moviesToSearch.Count;
				
			backgroundWorker.RunWorkerAsync(moviesToSearch);
		}
		
		void FilesDataGridViewCellValueChanged(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex >= 0 && (e.ColumnIndex == matchedMoviesColumn.Index || e.ColumnIndex == mediaTypeColumn.Index))
			{
				DataGridViewRow row = filesDataGridView.Rows[e.RowIndex];
				MovieFile movieFile = (MovieFile)row.DataBoundItem;
				movieFile.GenerateDestName();
			}
		}
		
		void FilesDataGridViewCurrentCellDirtyStateChanged(object sender, EventArgs e)
		{
			if (filesDataGridView.CurrentCell != null && 
			    filesDataGridView.CurrentCell.RowIndex >=0 && 
			    (filesDataGridView.CurrentCell.ColumnIndex == matchedMoviesColumn.Index || filesDataGridView.CurrentCell.ColumnIndex == mediaTypeColumn.Index || filesDataGridView.CurrentCell.ColumnIndex == renameColumn.Index) &&
			    filesDataGridView.IsCurrentCellDirty)
		    {
		        filesDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
		    }			
		}
		
		void RenameToolButtonClick(object sender, EventArgs e)
		{
			foreach (DataGridViewRow row in filesDataGridView.Rows)
			{
				bool rename = (bool)((DataGridViewCheckBoxCell)row.Cells["renameColumn"]).Value;
				if (rename)
				{
					MovieFile movieFile = row.DataBoundItem as MovieFile;
					
					if (File.Exists(movieFile.FullDestFileName))
					{
						if (MessageBox.Show(this, string.Format("File \"{0}\" already exists. Do you want to replace it?", movieFile.FullDestFileName), "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
						{
							//File.Delete(movieFile.FullDestFileName);
						}
					}
					
					if (File.Exists(movieFile.FullFileName) && !File.Exists(movieFile.FullDestFileName))
					{
						File.Move(movieFile.FullFileName, movieFile.FullDestFileName);
					}
					
					filesDataGridView.Rows.Remove(row);
				}
			}
		}
		
		
		void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
		{
			ArrayList moviesToSearch = e.Argument as ArrayList;
			foreach (MovieFile movieFile in moviesToSearch)
			{
				backgroundWorker.ReportProgress(0, movieFile.FileName);
				Utils.FindMatchedMovies(movieFile);
				backgroundWorker.ReportProgress(1);
			}
		}
		
		void BackgroundWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			if (e.UserState != null)
			{
				statusLabel.Text = string.Format("Searching matches for \"{0}\"...", e.UserState.ToString());
			}
			
			statusProgressBar.Increment(e.ProgressPercentage);
		}
		
		void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			if (e.Error == null)
			{
				DataGridViewCell currentCell = filesDataGridView.CurrentCell;
				foreach (DataGridViewRow row in filesDataGridView.Rows)
				{
					MovieFile movieFile = (MovieFile)row.DataBoundItem;
					if (movieFile.Rename)
					{
						ArrayList matchedMovies = movieFile.MatchedMovies;
						
						DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)row.Cells["matchedMoviesColumn"];
						filesDataGridView.CurrentCell = cell;
						
						cell.DisplayMember = "DisplayTitle";
						cell.ValueMember = "Self";
						cell.DataSource = matchedMovies;
						
						if (matchedMovies != null && matchedMovies.Count > 0)
						{
							cell.Value = matchedMovies[0];
						}
					}
				}
				filesDataGridView.CurrentCell = currentCell;
			}
			
			statusLabel.Text = string.Empty;
			statusProgressBar.Visible = false;
			
			Cursor = Cursors.Arrow;
		}
	}
}
